/**   
 *    
 * 项目名称：SmartKungFuService   
 * 类名称：ProjectInfoServlet   
 * 类描述：   活动详情
 * 创建人：zhanghl   
 * 创建时间：2016年10月25日 下午5:12:18   
 * 修改人：zhanghl   
 * 修改时间：2016年10月25日 下午5:12:18   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.servlet;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.dao.ClientAccomplishMapper;
import com.lst.dao.MstCodeMapper;
import com.lst.entity.request.ProjectInfoReqPara;
import com.lst.entity.response.ProjectInfoResPara;
import com.lst.model.ClientAccomplish;
import com.lst.model.ClientGrowthUsed;
import com.lst.model.ClientNum;
import com.lst.model.ClientRoll;
import com.lst.model.MstCode;
import com.lst.model.MstGrade;
import com.lst.model.MstOrder;
import com.lst.model.MstRoll;
import com.lst.model.MstSchedule;
import com.lst.model.OrderDetail;
import com.lst.model.ProjectInfo;
import com.lst.service.ClientGrowthUsedService;
import com.lst.service.ClientNumService;
import com.lst.service.ClientRollService;
import com.lst.service.MstGradeService;
import com.lst.service.MstOrderService;
import com.lst.service.MstRollService;
import com.lst.service.OrderDetailService;
import com.lst.service.ProjectInfoService;
import com.lst.utils.CommFunUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: ProjectInfoServlet
 * @Description: 活动详情
 * @author zhanghl
 * @date 2016年10月25日 下午5:12:18
 *
 */
public class ProjectInfoServlet extends BaseServlet {

	/**ee
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private ProjectInfoService projectInfoService = ctx.getBean(ProjectInfoService.class); 

//	private ClientRollService clientRollService = ctx.getBean(ClientRollService.class); 

//	private MstRollService mstRollService = ctx.getBean(MstRollService.class);

//	private ClientGrowthUsedService clientGrowthUsedService = ctx.getBean(ClientGrowthUsedService.class);

//	private MstGradeService mstGradeService = ctx.getBean(MstGradeService.class);

	private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);

	private MstOrderService mstOrderService = ctx.getBean(MstOrderService.class);

	private OrderDetailService orderDetailService = ctx.getBean(OrderDetailService.class);

//	private ClientAccomplishMapper clientAccomplishMapper = ctx.getBean(ClientAccomplishMapper.class);

	private MstCodeMapper mstCodeMapper = ctx.getBean(MstCodeMapper.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		ProjectInfoResPara resPara = new ProjectInfoResPara();

		try {
			ProjectInfoReqPara reqPara = getReqPara(request);

			if(isCheckField(reqPara,resPara)){
				Integer pid = Integer.valueOf(reqPara.getPid());				
			//	Integer type = Integer.valueOf(reqPara.getType());//优惠券类型
				String userid = reqPara.getUserid();
				//String Grade = reqPara.getGrade();

				PageBounds pageBounds = new PageBounds();

				//活动详情
				ProjectInfo p = projectInfoService.selectByPrimaryKey(pid);

				MstCode mc = mstCodeMapper.selectByPrimaryKey(p.getProtype());
				p.setProtypename(mc.getName());

				p.setWarning(CommFunUtils.formatStr(p.getWarning(), "• ", "\r\n"));
				p.setLightspot((CommFunUtils.formatStr(p.getLightspot(), "• ", "\r\n")));

				String starttime = StringUtils.isEmpty(p.getStartdate()) ? null : DateUtil.getFormatTime(p.getStartdate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
				String endtime = StringUtils.isEmpty(p.getEnddate()) ? null : DateUtil.getFormatTime(p.getEnddate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
				p.setStarttime(starttime);			
				p.setEndtime(endtime);

				//收藏量
				Integer favoritenum = CommFunUtils.opNum(null, p.getId(), CommCode.SYSTEM_CARESEL_RANGE_PRO, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
				//分享量
				Integer sharenum = CommFunUtils.opNum(null, p.getId(), CommCode.SYSTEM_CARESEL_RANGE_PRO, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
				//浏览量
				Map<String, Object> moMap = new HashMap<String, Object>();

				moMap.put("enabled", true);
				moMap.put("isDeleted", false);	
				moMap.put("numtype", CommCode.SYSTEM_COUNT_BROWSE);
				moMap.put("actid", pid);
				moMap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_PRO);

				List<ClientNum> browselist = clientNumService.queryByList(moMap);

				Integer browsenum = 0;

				for(ClientNum c : browselist){
					browsenum += c.getNum() == null ? 0 : c.getNum();
				}

				p.setFavoritenum(favoritenum);
				p.setSharenum(sharenum);
				p.setBrowsenum(browsenum);

				//获取剩余人数
				Map<String, Object> momap = new HashMap<String, Object>();

				momap.put("enabled", true);
				momap.put("isDeleted", false);
				momap.put("actid", pid);	
				momap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_PRO);

				List<MstOrder> moList =  mstOrderService.queryByList(momap, pageBounds);

				Integer countnum = 0;

				for(MstOrder m : moList){

					momap.clear();
					momap.put("enabled", true);
					momap.put("isDeleted", false);
					momap.put("orderid", m.getId());	

					List<OrderDetail> odlist = orderDetailService.queryByList(momap, pageBounds);

					if(CommCode.SYSTEM_ORDER_STATUS_WAIT.equals(odlist.get(0).getOrderstatus())){
						countnum += m.getNum() == null ? 0 : m.getNum();
					}
				}

				Integer leavenum = p.getReserved1() - countnum;

				if(leavenum>=0){
					p.setLeavenum(leavenum);
				}else{
					p.setLeavenum(0);
				}

				//倒计时天数
				if(!StringUtils.isEmpty(p.getStartdate())){

					Date startdate = DateUtil.getFormatDate(p.getStartdate(),DateUtil.ALL_DATE_HORIZONTAL);

					Date  currentDate = DateUtil.getFormatDate(new Date(), DateUtil.ALL_DATE_HORIZONTAL);

					int countdown = (int)((startdate.getTime()-currentDate.getTime())/86400000);

					if(countdown>0){
						p.setCountdown(countdown);
					}else {
						p.setCountdown(0);
					}
				}

				List<MstSchedule> dates = CommFunUtils.parseDatas(DateUtil.getFormatTime(p.getStartdate(), DateUtil.ALL_DATE_HORIZONTAL), DateUtil.getFormatTime(p.getEnddate(), DateUtil.ALL_DATE_HORIZONTAL));

				List<MstSchedule> times  = CommFunUtils.parseTimes(p.getPerdate(), p.getReserved9());

				resPara.setDates(dates);
				resPara.setTimes(times);

				//统计量
				List<ClientNum> cns = null;

				if(!StringUtils.isEmpty(userid)){
					Map<String, Object> cnmap = new HashMap<String, Object>();

					cnmap.put("enabled", true);
					cnmap.put("isDeleted", false);
					cnmap.put("clientid", Integer.valueOf(userid));
					cnmap.put("numtype",CommCode.SYSTEM_COUNT_FAVORITE);
					cnmap.put("actid", pid);
					cnmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_PRO);

					cns = clientNumService.queryByList(cnmap);				
				}

				if(null==cns||cns.size()==0){
					p.setIsFavorite(false);					
				}else{
					p.setIsFavorite(true);						
				}

				resPara.setPi(p);

				//更多活动
				Map<String, Object> piMap = new HashMap<String, Object>();

				piMap.put("enabled", true);
				piMap.put("isDeleted", false);
				piMap.put("orderByClause", "pi.updatedate desc");	
				piMap.put("start", 0);
				piMap.put("size", 6);

				List<ProjectInfo> pilist = projectInfoService.queryByList(piMap, pageBounds);

				ProjectInfo pi = null;
				for(ProjectInfo pro : pilist){
					if(pro.getId().equals(p.getId())){
						pi = pro;
						break;
					}	
				}
				if(pi == null){
					pilist.remove(pilist.get(pilist.size()-1));
					resPara.setPilist(pilist);					
				}else{
					pilist.remove(pi);
					resPara.setPilist(pilist);

				}

				//等级，优惠券
//				Map<String, Object> cgMap = new HashMap<String, Object>();
//
//				cgMap.put("enabled", true);
//				cgMap.put("isDeleted", false);
//
//				if(!StringUtils.isEmpty(userid)){
//
//
//					List<ClientAccomplish> caplist = clientAccomplishMapper.queryByUser(Integer.valueOf(userid));
//                    if(caplist!=null&caplist.size()>0){
//                    	Integer grade = caplist.get(0).getGrade();// 等级
//                    	//我的等级
//    					cgMap.put("clientid", Integer.valueOf(userid));
//    					cgMap.put("gradeid", grade);
//
//    					List<ClientGrowthUsed> cglist = clientGrowthUsedService.queryByList(cgMap, pageBounds); 
//
//    					if(cglist.isEmpty()){
//
//    						List<MstGrade> mgs = mstGradeService.queryByList(cgMap, pageBounds);
//    						resPara.setMstgrade(mgs.get(0));
//    					}
//
//    					//我的优惠券
//    					Map<String, Object> mstMap = new HashMap<String, Object>();
//
//    					mstMap.put("enabled", true);
//    					mstMap.put("isDeleted", false);				
//    					mstMap.put("pid", pid);
//    					mstMap.put("type", type);
//    					mstMap.put("orderByClause", "mr.createdate desc");
//
//    					List<MstRoll> mrlist = 	mstRollService.queryByList(mstMap, pageBounds);
//
//    					List<MstRoll> mstrolllist = null;
//
//    					if(!mrlist.isEmpty()){
//
//    						mstrolllist = new ArrayList<MstRoll>();
//
//    						Map<String, Object> crMap = new HashMap<String, Object>();
//
//    						crMap.put("enabled", true);
//    						crMap.put("isDeleted", false);
//    						crMap.put("clientid", Integer.valueOf(userid));
//
//    						for(MstRoll mr : mrlist){						
//
//    							crMap.put("rollid", mr.getId());
//
//    							List<ClientRoll> crlist = clientRollService.queryList(crMap, pageBounds);
//
//    							if(crlist.isEmpty()){//查询当前可用
//    								Date start = DateUtil.getFormatDate(mr.getStartdate(),DateUtil.ALL_DATE_HORIZONTAL);
//
//    								Date end = DateUtil.getFormatDate(mr.getEnddate(),DateUtil.ALL_DATE_HORIZONTAL);
//
//    								Date  currentDate = DateUtil.getFormatDate(startDate, DateUtil.ALL_DATE_HORIZONTAL);
//
//    								int days1 = (int)((currentDate.getTime()-start.getTime())/86400000);
//
//    								int days2 = (int)((end.getTime()-currentDate.getTime())/86400000);
//
//    								if(days1>=0&&days2>=0){
//
//    									mstrolllist.add(mr);
//    								}
//    							}
//    						}						
//    					}
//    					resPara.setMrList(mstrolllist);
//                    }
//				}
				
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);
			}

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
			logger.info(jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public ProjectInfoReqPara getReqPara(HttpServletRequest request) {

		ProjectInfoReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new ProjectInfoReqPara());

			reqPara = (ProjectInfoReqPara) baseRequest.clone();
		//	String page = request.getParameter("page");
		//	String pagesize = request.getParameter("pagesize");
		//	String searchwork = request.getParameter("searchwork");
		//	String type=request.getParameter("type");
			String pid=request.getParameter("pid");
			String userid=request.getParameter("userid");

//			logger.info("reqPara page: " + page);
//			logger.info("reqPara pagesize: " + pagesize);
//			logger.info("reqPara searchwork: " + searchwork);
			logger.info("reqPara pid: " + pid);
			logger.info("reqPara userid: " + userid);

//			reqPara.setPage(page);
//			reqPara.setPagesize(pagesize);
//			reqPara.setSearchwork(searchwork);
     		reqPara.setPid(pid);
     		reqPara.setUserid(userid);
//	        reqPara.setType(type);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		ProjectInfoReqPara piReqPara = (ProjectInfoReqPara) reqPara;
		ProjectInfoResPara piResPara = (ProjectInfoResPara) resPara;

		if (StringUtils.isEmpty(piReqPara.getPid())) {
			piResPara.setCode(CommCode.M_A000000);
			piResPara.setMessage(CommCode.M_E000025);
		} else if(StringUtils.isEmpty(piReqPara.getUserid())){
			piResPara.setCode(CommCode.M_A000000);
			piResPara.setMessage(CommCode.M_P000002);
		} else {
			flag = true;
		}
		return  flag;
	}
}
